import axios from 'axios'
import useUserStore from '@g/store/modules/user'
import { ikStore } from 'iking-utils'

const getSearchParam = (key: string) => {
  const searchStr = window.location.search
  const objParams = new URLSearchParams(searchStr)
  return objParams.get(key)
}

const setNormalDomainHeader = (headers: any) => {
  const userStore = useUserStore()
  const domain = userStore.getXDomain()
  if (!domain) {
    //
    return
  }
  headers['X-DOMAIN'] = domain
}

const setDomainHeader = (headers: any) => {
  const userStore = useUserStore()
  const domain = getSearchParam('domain')
  if (domain) {
    headers['X-DOMAIN'] = domain
    const code = getSearchParam('code')
    if (domain === 'APPLICATION') {
      //
      headers['X-APP'] = code
    }
    else if (domain === 'TENANT_MANAGEMENT') {
      // 租户 值已经在登录时赋上了
      headers['X-TENANT'] = userStore?.tenant?.code || ikStore.local.getItem(ELocal.TENANT)?.code
    }
  }
  else {
    setNormalDomainHeader(headers)
  }
}

axios.interceptors.request.use((config: any) => {
  const userStore = useUserStore()
  if (userStore.serviceVersion === '2') {
    // 如果服务是版本为 v2 则设置域标识
    setDomainHeader(config.headers)
  }
  return config
})
